package com.pair.micro.common.network.intercepter;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

@Slf4j
public class MicroRetryInterceptor implements Interceptor {

  public int maxRetry; // 最大重试次数
  private int retryNum = 0; // 假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

  public MicroRetryInterceptor(int maxRetry) {
    this.maxRetry = maxRetry;
  }

  @Override
  public Response intercept(Chain chain) throws IOException {
    return retry(chain);
  }

  public Response retry(Chain chain) {
    Response response = null;
    Request request = chain.request();
    try {
      response = chain.proceed(request);
      while (!response.isSuccessful() && retryNum < maxRetry) {
        retryNum++;
        response = retry(chain);
      }
    } catch (Exception e) {
      while (retryNum < maxRetry) {
        retryNum++;
        response = retry(chain);
      }
    }
    return response;
  }
}
